package com.wwj.auction.login.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wwj.auction.common.enums.UserBindEnum;
import com.wwj.auction.common.result.exception.BusinessException;
import com.wwj.auction.login.entity.UserAccount;
import com.wwj.auction.login.entity.UserBind;
import com.wwj.auction.login.entity.UserInfo;
import com.wwj.auction.login.entity.vo.UserBindVO;
import com.wwj.auction.login.fhb.FormHelper;
import com.wwj.auction.login.fhb.HfbConst;
import com.wwj.auction.login.fhb.RequestHelper;
import com.wwj.auction.login.mapper.UserAccountMapper;
import com.wwj.auction.login.mapper.UserBindMapper;
import com.wwj.auction.login.mapper.UserInfoMapper;
import com.wwj.auction.login.service.UserBindService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户绑定表 服务实现类
 * </p>
 *
 * @author wwj
 * @since 2021-08-10
 */
@Service
public class UserBindServiceImpl extends ServiceImpl<UserBindMapper, UserBind> implements UserBindService {

    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private UserAccountMapper userAccountMapper;

    @Override
    public String commitBindUser(UserBindVO userBindVO, Long userId) {
        // 查询输入的身份证是否已经被绑定
        UserBind userBind = baseMapper.selectOne(
                new LambdaQueryWrapper<UserBind>()
                        .eq(UserBind::getIdCard, userBindVO.getIdCard())
                        .ne(UserBind::getUserId, userId));
        if (userBind != null) {
            // 若已被绑定，则抛出异常
            throw new BusinessException("身份证已经被绑定");
        }
        // 校验用户是否已经绑定过
        userBind = baseMapper.selectOne(
                new LambdaQueryWrapper<UserBind>()
                        .eq(UserBind::getUserId, userId));
        if (userBind == null) {
            // 若用户未绑定，则执行绑定流程
            userBind = new UserBind();
            // 属性拷贝
            BeanUtils.copyProperties(userBindVO, userBind);
            // 设置主键id
            userBind.setUserId(userId);
            // 初始状态设置为未绑定
            userBind.setStatus(UserBindEnum.NO_BIND.getStatus());
            // 保存
            baseMapper.insert(userBind);
        } else {
            // 若用户已经绑定过，则更新绑定信息
            BeanUtils.copyProperties(userBindVO, userBind);
            baseMapper.updateById(userBind);
        }

        // 封装汇付宝接口需要的参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("agentId", HfbConst.AGENT_ID);
        paramMap.put("agentUserId", userId);
        paramMap.put("idCard", userBindVO.getIdCard());
        paramMap.put("personalName", userBindVO.getName());
        paramMap.put("bankType", userBindVO.getBankType());
        paramMap.put("bankNo", userBindVO.getBankNo());
        paramMap.put("mobile", userBindVO.getMobile());

        paramMap.put("returnUrl", HfbConst.USERBIND_RETURN_URL);
        paramMap.put("notifyUrl", HfbConst.USERBIND_NOTIFY_URL);

        paramMap.put("timestamp", RequestHelper.getTimestamp());
        paramMap.put("sign", RequestHelper.getSign(paramMap));

        // 生成动态表单字符串
        return FormHelper.buildForm(HfbConst.USERBIND_URL, paramMap);
    }

    @Override
    public void notify(Map<String, Object> paramMap) {
        String bindCode = (String) paramMap.get("bindCode");
        String agentUserId = (String) paramMap.get("agentUserId");
        // 根据userId查询userBind
        UserBind userBind = baseMapper.selectOne(
                new LambdaQueryWrapper<UserBind>()
                        .eq(UserBind::getUserId, agentUserId));
        userBind.setBindCode(bindCode);
        // 绑定状态设置为已绑定
        userBind.setStatus(UserBindEnum.BIND_OK.getStatus());
        // 更新用户绑定表
        baseMapper.updateById(userBind);

        // 更新用户表
        UserInfo userInfo = userInfoMapper.selectById(agentUserId);
        userInfo.setBindCode(bindCode);
        userInfo.setName(userBind.getName());
        userInfo.setIdCard(userBind.getIdCard());
        userInfo.setBindStatus(UserBindEnum.BIND_OK.getStatus());
        userInfoMapper.updateById(userInfo);

        // 开户前先判断当前用户的手机号是否已经开户
        UserAccount userAccount = userAccountMapper.selectOne(
                new LambdaQueryWrapper<UserAccount>()
                        .eq(UserAccount::getPhone, userInfo.getPhone()));
        if (userAccount == null) {
            // 若未开户，则执行开户流程
            userAccount = new UserAccount();
            // 设置用户id
            userAccount.setUserId(userInfo.getId());
            userAccount.setPhone(userInfo.getPhone());
            // 初始账户余额与冻结金额均为0
            userAccount.setAmount(new BigDecimal("0"));
            userAccount.setFreezeAmount(new BigDecimal("0"));
            userAccountMapper.insert(userAccount);
        } else {
            // 若已开户，则抛出异常
            throw new BusinessException("您的手机号已经开过户了");
        }
    }
}
